import {reqAddOrUpdateTrademark, reqDeleteTrademark, reqGetTrademarkList} from "@/api/trademark";
import {TrademarkData} from "@/api/trademark/modules/trademarkList";
import {Button, Card, Table, Image, Modal, Input, Form, Upload, UploadProps, UploadFile, message} from "antd";
import { ColumnsType } from "antd/es/table";
import {EditOutlined, DeleteOutlined, LoadingOutlined, PlusOutlined} from "@ant-design/icons";
import React, { useEffect, useState } from "react";
import { UploadChangeParam, RcFile } from "antd/lib/upload";
import { isJsxOpeningLikeElement } from "typescript";
import { useForm } from "antd/es/form/Form";

export default function TrademarkList(){
    // 分页列表相关状态
    let [total, setTotal] = useState(50);
    let [pageSize, setPageSize] = useState(3);
    let [current, setCurrent] = useState(1);
    let [loading, setLoading] = useState(false);
    // 点击添加显示弹框状态
    let [lookModal, setLookModal] = useState(false);
    // 上传图片
    let [tmName, setTmName] = useState('');
    let [logoUrl, setLogoUrl] = useState('');
    let [uid, setUid] = useState<number | string>();

    // const [tmList, setTmList] = useState<TrademarkData>({
    //     tmName,
    //     logoUrl
    // })

    // 品牌管理的列表数据
    let [trademarkData, setTrademarkData] = useState<TrademarkData[]>([]);

    // 声明品牌结构对象
    let columns: ColumnsType<any> = [
        {
            title: '序号',
            width: 70,
            align: 'center',
            render: (x: any, y: any, index: number) => {
                return index + 1;
            }
        },
        {
            title: '品牌名称',
            width: 200,
            dataIndex: 'tmName'
        },
        {
            title: '品牌LOGO',
            // dataIndex: 'logoUrl', //render中拿的是数组的每一项, 而dataIndex拿的是数组中具体的那一项
            render: (row: TrademarkData) => {
                return <Image width={80} src={row.logoUrl} alt={row.tmName} />
            }
        },
        {
            title: '操作',
            // render的参数: index, row, data
            render: (row: TrademarkData) => {
                return (
                    <div>
                        <Button onClick={update(row)} icon={<EditOutlined />} type="primary" >修改</Button>
                        <span className="ml5"></span>
                        <Button onClick={deleteOne(row)} icon={<DeleteOutlined />}  type="primary" danger>删除</Button>
                    </div>
                )
            }
        }
    ];

    // 1.获取分页列表数据
    let getTrademarkList = async (page = current, limit = pageSize) => {
        setLoading(true);
        const result = await reqGetTrademarkList(page, limit);
        // console.log(result);
        setLoading(false);
        setTrademarkData(result.records);
        setTotal(result.total);
    }

    // 点击添加按钮显示弹框
    const showModal = () => {
        // 每次添加前清空信息
        form.resetFields();
        setTmName('');
        setLogoUrl('');
        setLookModal(true);
    };

    // 点击修改
    const update =  (row: TrademarkData) => {
        return async () => {
            setLookModal(true);
            // setTmName(row.tmName);
            setLogoUrl(row.logoUrl);
            // form.setFieldsValue({...row});
            // console.log(row);
            form.setFieldsValue({ 'tmName': row.tmName,"logoUrl":[{response:{data:row.logoUrl}}]});
            setUid(row.id);
        }
    }

    // 点击删除
    const deleteOne = (row: TrademarkData) => {
        return async () => {
            await reqDeleteTrademark(row.id as number);
            message.success('删除成功');
            getTrademarkList(trademarkData.length > 1 ? current : current - 1);
        }
    }

    //点击取消按钮关闭弹框
    const handleCancel = () => {
        setLookModal(false);
    };

    // 上传图片前的回调 (限制图片格式和大小)
    const beforeUpload = (file: RcFile) => {
        const isJpg = file.type === 'image/jpeg' || file.type === 'image/jpg';
        if (!isJsxOpeningLikeElement) {
            message.error('上传的图片必须是jpg!');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            message.error('上传的图片不能大于2MB!');
        }
        return isJpg && isLt2M;
    };

    const getBase64 = (img: RcFile, callback: (url: string) => void) => {
        const reader = new FileReader();
        reader.addEventListener('load', () => callback(reader.result as string));
        reader.readAsDataURL(img);
        
    };
    // 图片上传成功的回调
    const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
        if (info.file.status === 'done') {
            // getBase64(info.file.originFileObj as RcFile, url => {
            //     setLoading(false);
            //     setLogoUrl(url);
            //     message.success('已上传')
            //     // console.log(info)
            //     // console.log(info.file.response.data)
            // });
            setLoading(false);
            setLogoUrl(info.file.response.data);
        }
    };

    const normFile = (e: any) => {
        if(Array.isArray(e)){
            return e;
        }
        return e && e.fileList;
        // return e && e.logoUrl;
    }

    // 上传图片位置的按钮
    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>上传图片</div>
        </div>
    );

    // 收集表单元素
    let [form] = useForm();

    // 点击确定发请求
    let finish = async () => {
        
        //  tmName = form.getFieldValue('tmName');
        //  logoUrl = form.getFieldValue('logoUrl');
        // console.log(logoUrl[0].response.data)
        // setLogoUrl(logoUrl[0].response.data);
        // const values = {
        //     tmName,
        //     logoUrl
        // }
        let values = form.getFieldsValue();
        
        let newObj = {
            id: uid,
            tmName: values.tmName,
            logoUrl
        }
        // console.log(newObj);
        if(!tmName || !logoUrl){
            form.validateFields(['tmName', 'logoUrl']);
        }else{
            try {
                await reqAddOrUpdateTrademark(newObj);
                message.success(newObj.id ? '修改成功' : '添加成功');
                setLookModal(false);
                getTrademarkList(newObj.id ? current : 1);
                setCurrent(newObj.id ? current : 1);
            } catch (error) {
                message.success(newObj.id ? '修改失败' : '添加失败');
            }
        }
        
    }

    useEffect(() => {
        getTrademarkList(current, pageSize)
    }, [])  
         
    return (
        <Card>
            <Form form={form}  >
                <Modal width={600} title="添加品牌" open={lookModal} onOk={ finish} onCancel={handleCancel}>
                    <Form.Item 
                        name="tmName"
                        label="品牌名称:" 
                        rules={ [
                            {required: true, 
                             message: '请输入品牌名称'
                            }
                        ]} >
                            <Input name="tmName" value={tmName} 
                                width={300} placeholder="品牌名称长度为6-20"
                                onChange={ (e) => { setTmName(e.target.value)}}
                            ></Input>
                    </Form.Item>
                    <Form.Item 
                        name="logoUrl"
                        label="品牌LOGO:"  
                        // valuePropName="logoUrl" 
                        valuePropName="fileList" 
                        getValueFromEvent={normFile} 
                        rules={ [{required: true, message: '请上传品牌图片'}] }>
                            <Upload
                                name='file'
                                listType="picture-card"
                                className="avatar-uploader"
                                showUploadList={false}
                                action="http://gmall-h5-api.atguigu.cn/admin/product/upload"
                                beforeUpload={beforeUpload}
                                onChange={handleChange}>
                                {logoUrl ? <img src={logoUrl} style={{ width: '100%' }} /> : uploadButton}
                            </Upload>
                    </Form.Item>
                        
                </Modal>
            </Form>
            <Button onClick={showModal} type="primary" >添加</Button>
            <div className="h-10"></div>
            <Table loading={loading}
                rowKey="id"
                bordered
                dataSource={trademarkData} 
                columns={columns} 
                pagination={{
                    total: total,
                    pageSize,
                    current,
                    showQuickJumper: true,
                    showSizeChanger: true,
                    pageSizeOptions: [3, 5, 10, 15],
                    showTotal: (total) => {
                        return <span>总计 {total} 条</span>;
                    },
                    // 点击页码切换
                    onChange: (current: number, pageSize: number) => {
                        // 修改页码与每页显示数量的状态
                        setCurrent(current);
                        setPageSize(pageSize);
                        getTrademarkList(current, pageSize);
                    }
                }}
            />
        </Card>)
}
